<template>
    <div class="main_container">
        <div v-if="pageName=='index'">
            <el-form :model="queryParams" label-width="auto">
                <el-row>
                    <el-col :span="7">
                        <el-form-item label="订单类型:">
                            <el-select style="width: 200px;" v-model="queryParams.record_type" @change="typeChange"
                                placeholder="请选择">
                                <el-option  label="销售单" :value="1"></el-option>
                                <el-option  label="退货单" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="关键词:">
                            <el-input style="width: 200px;" maxlength="100" v-model="queryParams._search" placeholder="订单编号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="客户:">
                            <div class="choose_border" @click="chooseCustomers()">
                                <span style="color: #c0c4cf;" v-if="!customer_name">请选择</span>
                                <span>{{ customer_name }}</span>
                                <i class="el-icon-circle-close icon" @click.stop="clearValue('customer')"></i>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button size="small" icon="el-icon-search" @click="handleQuery"
                            style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="7">
                        <el-form-item label="经办人:">
                            <div class="choose_border" @click="chooseUsers('handler')">
                                <span style="color: #c0c4cf;" v-if="!handler_name">请选择</span>
                                <span>{{ handler_name }}</span>
                                <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="开单日期:">
                            <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                                v-model="queryParams.create_datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                                placeholder="请选择时间区间" style="width: 240px;" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-row :gutter="16" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    v-hasPermi="['customer_receive_add']"
                    class="btn_primary_color"
                    icon="el-icon-plus"
                    size="small"
                    @click="handleAdd"
                    >新增</el-button>
                </el-col>
            </el-row>
            <el-table border :data="orderList" style="margin-top: 15px;" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="单据编号" align="left" prop="corp_order_no" />
                <el-table-column label="客户名称" align="left" prop="customer_name" />
                <el-table-column label="客户电话" align="left" prop="customer_phone" />
                <el-table-column label="收款金额" align="left" prop="orders_fee_name" />
                <el-table-column label="收款账户" align="left" prop="pay_type_name" />
                <el-table-column label="开单日期" align="left" prop="orders_date" />
                <el-table-column label="经办人" align="left" prop="handler_name" />
                <el-table-column label="操作" min-width="80" align="left" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleView(scope.row)"
                            style="font-weight: bold;"
                        >查看</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            v-hasPermi="['customer_receive_update']"
                            @click="handleEdit(scope.row)"
                            style="font-weight: bold;"
                        >编辑</el-button>
                        <el-button
                            v-hasPermi="['customer_receive_remove']"
                            size="mini"
                            type="text"
                            @click="handleRemove(scope.row)"
                            style="font-weight: bold;"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="getOrders"
                @current-change="getOrders"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增页面 -->
        <common-dialog :visiable="pageName == 'add'">
            <add :corpId="corp_id" :cusInfo="customerInfo" @success="success" @hidden="hidden"></add>
        </common-dialog>

        <!-- 编辑页面 -->
        <common-dialog :visiable="pageName == 'edit'">
            <add :corpId="corp_id" :editId="editId" @success="success" @hidden="hidden"></add>
        </common-dialog>

        <!-- 查看 -->
        <common-dialog :visiable="pageName == 'query'">
            <query :corpId="corp_id" :editId="editId" @hidden="hidden"></query>
        </common-dialog>

        <!-- 选择销售人员 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="selectedUsers.users"
            :title="selectedUsers.title"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>

        <!-- 选择客户 -->
        <choose-customer
            :showChooseCustomer="showChooseCustomerAlert"
            :selectUsers="customerList"
            @chooseOK="chooseCustomerOK"
            @hidden="showChooseCustomerAlert=false"
        ></choose-customer>
    </div>
</template>

<script>
import commonDialog from "@/components/commonDialog";
import { getCustomerList } from "@/api/cooperate";
import { getUserList } from "@/api/user";
import { getReceivePaymentList, removeReceivePayment } from "@/api/cooperate";
import chooseUser from "@/components/chooseUser";
import chooseCustomer from "@/components/chooseCustomer";

export default {
    name: 'receiveOrder',
    data() {
        return {
            showLoading: false,
            showChooseUserAlert: false,
            showChooseCustomerAlert: false,
            userType: '',
            multiple: true, // 非多个禁用
            exportLoading: false,
            showCustomerInfo: false,
            corp_id: '',
            editId: '',
            pageName: 'index',
            customer_name: '',
            customerInfo: {},
            handler_name: '',
            queryParams: {
                _search: '',
                customer_id: '',
                handler_user_id: '',
                record_type: 1,
                create_datetime: [],
                orders_date__lte: '',
                orders_date__gte: ''
            },
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            orderList: [],
            handlersList: [],
            customerList: [],
            cateLists: [],
            cateEditDialogTitle: '',
            viewForm: {},
            selectIds: []
        }
    },
    computed: {
        selectedUsers() {
            let users = []
            if (this.queryParams.handler_user_id){
                users = [{id: this.queryParams.handler_user_id}]
            }
            let title = '选择经办人'
            return {
                users, title
            }
        }
    },
    components: {
        commonDialog,
        chooseUser,
        chooseCustomer,
        add: () => import('./edit.vue'),
        query: () => import('./query.vue')
    },
    watch: {
        '$route.query.bussId2': {
            immediate: true, // 首次加载时触发
            handler(newId) {
                if (newId) {
                    this.pageName = 'query'
                    this.editId = null
                }
            }
        }
    },
    created() {
        this.corp_id = this.$store.state.corpId
        this.handleQuery()
        if (this.$route.query.cusId){
            this.pageName = 'add'
            this.customerInfo = {
                id: this.$route.query.cusId,
                name: this.$route.query.cusName
            }
        }
    },
    methods: {
        typeChange() {
            this.orderList = []
            this.handleQuery()
        },
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.getOrders()
        },
        chooseUsers(type) {
            this.userType = type
            this.showChooseUserAlert = true
        },
        chooseCustomers() {
            this.showChooseCustomerAlert = true
        },
        clearValue(type) {
            if (type == 'customer'){
                this.queryParams.customer_id = ''
                this.customer_name = ''
            }else {
                this.queryParams.handler_user_id = ''
                this.handler_name = ''
            }
        },
        chooseUserOK(res) {
            if (this.userType == 'handler'){
                this.queryParams.handler_user_id = res.length ? res[0].id : ''
                this.handler_name = res.length ? res[0].username : ''
            }
            this.showChooseUserAlert = false
        },
        chooseCustomerOK(res) {
            this.queryParams.customer_id = res.length ? res[0].id : ''
            this.customer_name = res.length ? res[0].name : ''
            this.showChooseCustomerAlert = false
        },
        getOrders() {
            this.queryParams.corp = this.corp_id
            let params = Object.assign({}, this.queryParams, this.pageParam)
            getReceivePaymentList(params).then(res => {
                this.orderList = res.data.data.orders_list.filter(item => {
                    item.customer_name = '未知客户'
                    if (item.customer_detail && item.customer_detail.customer_name){
                        item.customer_name = item.customer_detail.customer_name
                        item.customer_phone = item.customer_detail.phone
                    }
                    item.orders_fee_name = '￥'+item.orders_fee
                    item.pay_type_name = this.handlePayType(item.pay_type)
                    item.handler_name = item.handler_user_detail?item.handler_user_detail.username:''
                    return item
                })
                this.total = res.data.data.total
            })
        },
        handlePayType(type) {
            let name = ''
            switch (type) {
                case 1:
                    name = '现金'
                    break;
                case 2:
                    name = '微信'
                    break;
                case 3:
                    name = '银行转账'
                    break;
                case 4:
                    name = '其他'
                    break;
                case 5:
                    name = '支付宝'
                    break;
                default:
                    break;
            }
            return name
        },
        hidden(val) {
            this.pageName = 'index'
            if (this.$route.query.bussId2){
                this.$router.replace({ path: this.$route.path, query: {} });
            }
            if (val && val.isRefresh=='true'){
                this.handleQuery()
            }
        },
        success() {
            this.pageName = 'index'
            // 获取当前URL
            let url = window.location.href;
            // 使用正则表达式去除参数部分
            let newUrl = url.replace(/\?.*/, '');
            // 更新URL
            window.history.replaceState({}, '', newUrl);
            this.customerInfo = {}
            this.handleQuery()
        },
        // 新增
        handleAdd() {
            this.editId = null
            this.pageName = 'add'
        },
        // 编辑
        handleEdit(item) {
            this.editId = item.id
            this.pageName = 'edit'
        },
        // 查看
        handleView(item) {
            this.editId = item.id
            this.pageName = 'query'
        },
        // 删除所选
        handleRemoveSelect() {
            let that = this
            this.$confirm('您确定要删除选中的客户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeBatchCustomer({
                    corp_id: that.corp_id,
                    pk_id_list: that.selectIds
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 删除
        handleRemove(item) {
            let that = this
            this.$confirm('您确定要删除该收款单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeReceivePayment(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            // console.log(selection);
            this.multiple = !selection.length
            let ids = selection.map(item => item.id)
            this.selectIds = ids
        },
        // 选择客户
        personChange(value) {
            let [ id, name ] = value.split('&&')
            this.queryParams.customer_id = id
            this.customer_name = name
        },
        remoteMethodWithCustomer(query) {
            if (query !== '') {
                this.showLoading = true
                getCustomerList({
                    corp: this.corp_id,
                    category: '',
                    search: query
                }).then(res => {
                    this.showLoading = false
                    this.customerList = res.data.data.customer_list.filter(item => {
                        item.label = item.name
                        item.value = item.id+'&&'+item.name
                        if (item.category_detail && item.category_detail.name){
                            item.label += ('（'+item.category_detail.name+'）')
                        }
                        return item
                    });
                })
            } else {
                this.customerList = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            let [ id, username ] = value.split('&&')
            this.queryParams.handler_user_id = id
            this.handler_name = username
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.corp_id,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .cates_view {
        padding: 0 30px;
        .lists {
            margin-top: 15px;
            .item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                border-top: 1px solid #eee;
                margin-bottom: 10px;
                .name {
                    font-size: 14px;
                    color: #333;
                }
            } 
        }
    }
    .upload_view {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>
<style>
.el-drawer__header {
    font-weight: bold;
    color: #333;
    font-size: 15px;
}
.el-loading-spinner {
    top: 42% !important;
    color: #068CEE !important;
}
.el-loading-spinner .el-icon-loading {
    font-size: 34px !important;
    margin-bottom: 15px !important;
}
.el-loading-spinner .el-loading-text {
    font-size: 16px !important;
}
</style>